import re
from pathlib import Path
from core.backup import BackupManager
from plugins.template.adapter import PluginBase

class FedoraAdapter(PluginBase):
    def __init__(self):
        self.repo_dir = Path("/etc/yum.repos.d/")
        self.backup = BackupManager("fedora")
        self.version = self._get_fedora_version()

    @classmethod
    def is_compatible(cls) -> bool:
        return FedoraDetector().detect()

    def apply_mirror(self, mirror_url: str):
        """替换 Fedora 官方源为指定镜像"""
        for repo_file in self.repo_dir.glob("fedora*.repo"):
            self._modify_repo_file(repo_file, mirror_url)

    def _get_fedora_version(self) -> str:
        """从 VERSION_ID 提取主版本号 (e.g. '36' from '36')"""
        os_info = FedoraDetector().get_os_release()
        return os_info.get("VERSION_ID", "").split(".")[0]

    def _modify_repo_file(self, repo_path: Path, mirror_url: str):
        """修改单个 .repo 文件"""
        self.backup.create(repo_path)
        
        content = repo_path.read_text()
        # 注释 metalink
        content = re.sub(r"^metalink=.*$", "# metalink=Removed by mirror-tool", content, flags=re.MULTILINE)
        # 替换 baseurl
        content = re.sub(
            r"^#?\s*baseurl=.*$",
            f"baseurl={mirror_url}/fedora/releases/$releasever/Everything/$basearch/os/",
            content,
            flags=re.MULTILINE
        )
        repo_path.write_text(content)